package com.by.controller;

import com.by.bean.Product;
import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.common.utils.DateUtils;
import com.by.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
//包含产品保存的代码
@RestController
@Api(tags = "文件上传")
@RequestMapping("/v1")
public class UploadController extends BaseController {
    final String DIR = "/attachment";
    final Set<String> imgSet=new HashSet<>();

    @Autowired
    ProductService productService;

    /**
     * 初始化图片的类型
     */
    {
        imgSet.add("image/jpeg");
        imgSet.add("image/png");
    }


    /**
     * 上传图片
     *
     * @param file    要上传的文件
     * @param request 请求域对象  可以获取服务器存储目录
     * @return
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload/img")
    public ResultBean uploadImg(MultipartFile file, HttpServletRequest request,String name,String code) {
          //获取文件的类型
          String type=file.getContentType();
          if(!imgSet.contains(type))
              return fail("请上传：jpg、png格式的文件");
          String path=upload(file,request,"images");
        Map map =new HashMap<>();
        map.put("name",name);
        map.put("code",code);
//          productService.fileload(map);
//        String root = request.getServletContext().getRealPath("/");
//        System.out.println("服务器根目录: " + root); // 打印 root
          return success("上传成功",path);
    }
    @ApiOperation("查询类型")
    @GetMapping("/upload/type")
    public ResultBean querytype(){
        List list=productService.querytype();
        if (list==null){
            return  fail("无数据");
        }
        return success("查询成功",list);
    }
    @ApiOperation("产品保存")
    @PostMapping("/upload/save")
    public ResultBean saveproduct(@RequestBody Product product){
        int rs=productService.save(product);
        if (rs==1){
            return  success("成功");
        }
        return fail("失败");

    }


    /**
     * 上传图片
     *
     * @param file    要上传的文件
     * @param request 请求域对象  可以获取服务器存储目录
     * @return
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload/video")
    public ResultBean uploadVideo(MultipartFile file, HttpServletRequest request) {
        String path=upload(file,request,"video");
        return success("上传成功",path);
    }


    /**
     * 上传
     *
     * @param file
     * @param request
     * @param type
     * @return
     */
    private String upload(MultipartFile file, HttpServletRequest request, String type) {
        //原始文件名称
        String fileName = file.getOriginalFilename();
        //获取文件的后缀
        String ext = getExt(fileName);
        //生成新的文件名
        String newFileName = System.currentTimeMillis() + ext;

        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/");
        String tmpDir = DIR + "/" + type + "/" + DateUtils.getYmd();
        File dirFile = new File(root + tmpDir);
        if (!dirFile.exists())
            dirFile.mkdirs();//创建目录

        //将上传的文件拷贝到指定目录
        try {
            file.transferTo(new File(dirFile, newFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //上传成功
        String path = tmpDir + "/" + newFileName;
        return path;
    }


    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    String getExt(String fileName) {
        //获取.的位置
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);// 包含
    }
}
